<template>
  <el-dialog :title=" '复制'" v-model="visible" width="400px"
             :close-on-click-modal="false" draggable>
      <div class="dialog-content">
        <div class="content-row" v-for="(line, index) in contentLines" :key="index">
          <span>{{ line }}</span>
          <el-button
              text
              type="primary"
              icon="DocumentCopy"
              @click="copyLine(line)"
              class="copy-btn"
          ></el-button>
        </div>
      </div>
  </el-dialog>
</template>

<script setup lang="ts" name="deployDeplDockerInfoCopyDialog">
import { ref } from 'vue'
import { useMessage } from '/@/hooks/message'

const visible = ref(false)
const contentLines = ref([
  // '这是第一行文字内容',
  // '这是第二行文字内容',
  // '这是第三行文字内容'
])

const openDialog = (row) => {
  console.log("copyOpenDialog",row)
  visible.value = true
  contentLines.value=[
    row.containerName,
    `docker logs --tail 200 ${row.containerId.substring(0, 3)}`,
    `docker logs -f ${row.containerId.substring(0, 3)}`,
  ]
}

const copyLine = (text) => {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text)
        .then(() => {
          useMessage().success('已复制: ' + text)
        })
        .catch(err => {
          console.error('复制失败:', err)
          fallbackCopyText(text)
        })
  } else {
    fallbackCopyText(text)
  }
}

const fallbackCopyText = (text) => {
  const textarea = document.createElement('textarea')
  textarea.value = text
  textarea.style.position = 'fixed'  // 避免滚动到页面底部
  document.body.appendChild(textarea)
  textarea.select()

  try {
    const successful = document.execCommand('copy')
    if (successful) {
      useMessage().success('已复制: ' + text)
    } else {
      useMessage().error('复制失败')
    }
  } catch (err) {
    console.error('复制失败:', err)
    useMessage().error('复制失败')
  } finally {
    document.body.removeChild(textarea)
  }
}

defineExpose({ openDialog })
</script>

<style scoped>
.dialog-content {
  line-height: 2;
}
.content-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}
.copy-btn {
  margin-left: 10px;
}
</style>
